package com.gordon.wiki.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gordon.wiki.exception.BusinessException;
import com.gordon.wiki.exception.BusinessExceptionCode;
import com.gordon.wiki.mapper.DocMapper;
import com.gordon.wiki.pojo.Doc;
import com.gordon.wiki.service.DocService;
import com.gordon.wiki.utils.RedisUtil;
import com.gordon.wiki.utils.RequestContext;
import com.gordon.wiki.websocket.WebSocketServer;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.dom.DOMCryptoContext;

/**
 * @Projectname: wiki
 * @Filename: DocServiceImpl
 * @Author: GordonLo
 * @Data:2022/11/16 9:36
 * @Description: TODO
 */
@Service
public class DocServiceImpl extends ServiceImpl<DocMapper, Doc> implements DocService {

    @Autowired
    private DocMapper docMapper;

    @Autowired
    private RedisUtil redisUtil;

//    @Autowired
//    private WebSocketServer webSocketServer;

    @Autowired
    private WsService wsService;

    @Override
    public int increaseViewCount(int id) {
        return docMapper.increaseViewCount(id);
    }

    @Override
    public int increaseVoteCount(int id) {
        String ip = RequestContext.getRemoteAddr();
        Doc doc = docMapper.selectById(id);

        String logId = MDC.get("LOG_ID");

        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 3600 * 24)) {
            wsService.sendInfo("【" + doc.getName() + "】点赞了！", logId);
            return docMapper.increaseVoteCount(id);
        } else {
            wsService.sendInfo("【" + doc.getName() + "】已经被点过赞了！",logId);
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
    }

    @Override
    public int updateEbookInfo() {
        return docMapper.updateEbookInfo();
    }
}